package org.chinasoft.aspect;

import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.chinasoft.entity.User;
import org.chinasoft.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

@Component
@Aspect
public class LogAop {
    @Autowired
    private LogService logService;

    //    @Pointcut("execution(* org.chinasoft.controller.UserController.getUserList())")
    @Pointcut("execution(* org.chinasoft.controller..*.*(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object handlerControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed = pjp.proceed();
        try {
            // 获取被拦截的方法
            MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
            Method targetMethod = methodSignature.getMethod();
            // 如果方法上有log注解,代表将日志保存到数据库
            if (targetMethod.isAnnotationPresent(Log.class)) {
                // 当前时间
                Date currentTime = new Date(System.currentTimeMillis());

                // 获取Log注解中note信息
                String note = targetMethod.getAnnotation(Log.class).note();

                // 当前用户
                User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
                if (currentUser != null) {
                    // 产生日志,保存到数据库
                    org.chinasoft.entity.Log log = new org.chinasoft.entity.Log();
                    log.setUserId(currentUser.getUserId());
                    log.setNote(note);
                    log.setGmtCreated(currentTime);
                    logService.save(log);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return proceed;
    }
}
